import logging

import zhconv

from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError

_logger = logging.getLogger(__name__)


class DouyinVideo(models.Model):
    """抖音视频模型
    aweme应该就是视频
    """
    _name = 'douyin.video'
    _description = 'Douyin Video'
    _rec_name = 'title'

    aweme_id = fields.Char(string='Aweme ID', help='应该是视频的ID')
    title = fields.Char(string='Title', compute='_compute_title', store=True)
    title_tw = fields.Char(string='Title繁体', compute='_compute_title', store=True)
    preview_title = fields.Char(string='Preview Title')
    # 毫秒计算
    duration = fields.Float(string='Duration', help='视频时长')
    group_id = fields.Char(string='Group ID', help='合集首页，与mix_id不同')
    # 合集信息
    collection_id = fields.Many2one(
        comodel_name='douyin.collection', string='合集', ondelete='cascade', help='对应mix_info')
    create_time = fields.Datetime(string='发布时间')
    # statistics 统计信息
    play_count = fields.Integer(string='播放数量')
    collect_count = fields.Integer(string='收藏数量')
    comment_count = fields.Integer(string='品论数量')
    digg_count = fields.Integer(string='点赞数量')
    share_count = fields.Integer(string='分享数量')
    # 1080p aweme['video']['bit_rate'][0]['play_addr']['uri']
    # video_url = 'https://www.douyin.com/aweme/v1/play/?video_id='+uri
    video_uri = fields.Char(string='URI')
    file_id = fields.Char(string='File ID')
    sign = fields.Char(string='Sign')
    video_url = fields.Char(string='播放地址', compute='_compute_video_url')
    # 下载地址 720p
    download_url = fields.Char(string='下载链接(720p)')
    cover = fields.Char(string='Cover', help='封面，连接的过期时间为10年')
    # 视频可能没有合集，但是一定有作者
    author_id = fields.Many2one(comodel_name='douyin.author', string='作者', ondelete='cascade')
    current_episode = fields.Integer(string='集数')
    # 所属更新记录
    collection_update_history_id = fields.Many2one(
        comodel_name='douyin.collection.update.history', string='更新记录'
    )
    # 所属的合并视频
    merge_id = fields.Many2one(comodel_name='douyin.merge', string='所属合并视频')


    _sql_constraints = [
        ('aweme_id_uniq', 'unique (aweme_id)', 'Aweme ID是唯一的')
    ]

    @api.depends('video_uri')
    def _compute_video_url(self):
        for rec in self:
            video_url = f'https://www.douyin.com/aweme/v1/play/?video_id={rec.video_uri}'
            # 带file_id的连接打开时容易卡住，在网站上看下效果
            # if rec.file_id:
            #     # 兼容之前没有file_id的video记录
            #     video_url = f'{video_url}&file_id={rec.file_id}'
            rec.video_url = video_url

    @api.depends('preview_title')
    def _compute_title(self):
        for rec in self:
            title = rec.preview_title.split("#")[0]
            rec.update({
                'title': title,
                'title_tw': zhconv.convert(title, 'zh-tw')
            })